/*
 * @Author: Eureka 
 * @Date: 2022-01-20 11:21:57 
 * @Last Modified by: Eureka
 * @Last Modified time: 2022-01-21 11:36:31
 */
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:senkoo_platform/Utils/base_standard.dart';
import 'package:senkoo_platform/Utils/hex_color_utils.dart';
import 'package:senkoo_platform/Utils/set_edge_insets.dart';
import 'package:senkoo_platform/base_widget/base_gaps.dart';
import 'package:senkoo_platform/config/config.dart';
import 'package:senkoo_platform/iconfont/iconfont.dart';

/// 登录模块的输入框封装
class LoginTextField extends StatefulWidget {
  const LoginTextField(
      {Key? key,
      required this.controller,
      this.maxLength = 16,
      this.autoFocus = false,
      this.keyboardType = TextInputType.text,
      this.hintText = "",
      this.focusNode,
      this.isInputPwd = false,
      this.getVCode,
      this.config,
      this.leftIcon,
      this.keyName})
      : super(key: key);

  final TextEditingController controller;
  final int maxLength;
  final bool autoFocus;
  final TextInputType keyboardType;
  final String hintText;
  final FocusNode? focusNode;
  final bool isInputPwd;
  final Future<bool> Function()? getVCode;
  final KeyboardActionsConfig? config;
  final IconData? leftIcon;

  /// 用于集成测试寻找widget
  final String? keyName;

  @override
  _LoginTextFieldState createState() => _LoginTextFieldState();
}

class _LoginTextFieldState extends State<LoginTextField> {
  bool _isShowPwd = false;
  late bool _isShowDelete;

  @override
  void initState() {
    super.initState();

    /// 获取初始化值
    _isShowDelete = widget.controller.text.isNotEmpty;

    /// 监听输入改变
    widget.controller.addListener(isEmpty);
  }

  @override
  void dispose() {
    widget.controller.removeListener(isEmpty);
    super.dispose();
  }

  void isEmpty() {
    final bool isNotEmpty = widget.controller.text.isNotEmpty;

    /// 状态不一样在刷新，避免重复不必要的setState
    if (isNotEmpty != _isShowDelete) {
      setState(() {
        _isShowDelete = isNotEmpty;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget textField = TextField(
      cursorColor: Standard.color333333,
      style: TextStyle(
        color: Standard.color333333,
        fontSize: 14.sp,
      ),
      focusNode: widget.focusNode,
      maxLength: widget.maxLength,
      obscureText: widget.isInputPwd ? !_isShowPwd : false,
      autofocus: widget.autoFocus,
      controller: widget.controller,
      textInputAction: TextInputAction.done,
      keyboardType: widget.keyboardType,
      inputFormatters: (widget.keyboardType == TextInputType.number ||
              widget.keyboardType == TextInputType.phone)
          ? [FilteringTextInputFormatter.allow(RegExp("[0-9]"))]
          : [FilteringTextInputFormatter.deny(RegExp("[\u4e00-\u9fa5]"))],
      decoration: InputDecoration(
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Standard.colorCCCCCC, width: 0.0),
        ),
        border: OutlineInputBorder(
          borderSide: BorderSide(color: Standard.colorCCCCCC, width: 0.0),
        ),
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Standard.color000000, width: 0.0),
        ),
        contentPadding: setSymEdgeInsets(vertical: 14, horizontal: 14),
        hintText: widget.hintText,
        hintStyle: TextStyle(
          color: Standard.colorCCCCCC,
          fontSize: 14.sp,
        ),
        counterText: "",
      ),
    );

    /// 个别Android机型（华为、vivo）的密码安全键盘不弹出问题（已知小米正常），临时修复方法：https://github.com/flutter/flutter/issues/68571 (issues/61446)
    /// 怀疑是安全键盘与三方输入法之间的切换冲突问题。
    if (AppConfig.isAndroid) {
      textField = Listener(
        onPointerDown: (e) =>
            FocusScope.of(context).requestFocus(widget.focusNode),
        child: textField,
      );
    }

    Widget? clearButton;

    if (_isShowDelete) {
      clearButton = Semantics(
          label: '清空',
          hint: '清空输入框',
          child: GestureDetector(
            child: Container(
              width: 50.w,
              height: 50.w,
              alignment: Alignment.center,
              color: Colors.transparent,
              child: Icon(
                IconFont.iconpopcancel,
                color: HexColor('#C0CCDA'),
                size: 20.w,
              ),
            ),
            onTap: () => widget.controller.text = "",
          ));
    }

    return Container(
      constraints: BoxConstraints(
        maxHeight: 50.h,
        minHeight: 50.h,
      ),
      child: Stack(
        alignment: Alignment.centerRight,
        children: <Widget>[
          textField,
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Visibility(
                visible: _isShowDelete,
                child: clearButton ?? Gaps.empty,
              ),
            ],
          )
        ],
      ),
    );
  }
}
